# @decorator 装饰器 可直接捕获异常 写入日志
from functools import wraps
import traceback
import time
import logging
from conftest import BASE_DIR
import logging.handlers



def decorator(function):
    @wraps(function)
    def inner(*args, **kwargs):
        try:
            #print("当前运行方法", function.__name__)
            return function(*args, **kwargs)

        except Exception as e:
            # 获取logger
            logger = logging.getLogger()
            # 设置级别
            logger.setLevel(logging.INFO)
            th = logging.handlers.TimedRotatingFileHandler(
                BASE_DIR + "/error/{}.log".format(time.strftime('%Y-%m-%d--%H-%M')), when='D', interval=1,
                backupCount=0, encoding='utf-8')
            th.setLevel(logging.INFO)
            fmt = logging.Formatter('%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s')
            th.setFormatter(fmt)
            logger.addHandler(th)

            #print(e)
            logger.error(f"{function.__name__} is error,错误描述如下:{traceback.format_exc()}")
            #logger.error(e)
            assert False
    return inner




# logger = logging.getLogger(__name__)
# logger.setLevel(level=logging.INFO)
#
#
#
# def decorator(function):
#     @wraps(function)
#     def inner(*args, **kwargs):
#         try:
#             #print("当前运行方法", function.__name__)
#             return function(*args, **kwargs)
#         except Exception as e:
#             handler = logging.FileHandler(BASE_DIR + "/error/%s.log" % time.strftime('%Y-%m-%d--%H-%M'))
#             handler.setLevel(logging.INFO)
#             formatter = logging.Formatter('%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s')
#             handler.setFormatter(formatter)
#             logger.addHandler(handler)
#
#             #print(e)
#             #logger.error(f"{function.__name__} is error,here are details:{traceback.format_exc()}")
#             logger.error(f"{function.__name__} is error,错误描述如下:{traceback.format_exc()}")
#             #logger.error(e)
#             assert False
#     return inner
